var com = com||{};

com.init = function (){
	let scale = 1;
	if(window.innerWidth < 992)
		scale =	(window.innerWidth - 20) / 600;
	com.spaceX			=	40 * scale;
	com.spaceY			=	com.spaceX * Math.sqrt(3)/2;
	com.pointStartY		=	20 * scale;
	com.chessWidth		=	30 * scale;
	com.chessHeight		=	30 * scale;
	com.dotWidth		=	12 * scale;
	com.dotHeight		=	12 * scale;
	com.red = new Image();
	com.blue = new Image();
	com.paneImg = new Image();
	com.dot = new Image();
	com.red.src = "img/red.png";
	com.blue.src = "img/blue.png";
	com.paneImg.src  = "img/box.png";
	com.dot.src  = "img/dot.png";
	com.canvas = document.getElementById("canvas");
	com.canvas.width	=	600 * scale;
	com.canvas.height	=	600 * scale;
	com.ct = com.canvas.getContext("2d"); 
}
com.get = function (id){
	return document.getElementById(id)
}
window.onload = function(){
	let lastIp = localStorage.getItem("ip");
	if(!lastIp)
		lastIp = "localhost";
	com.get("ipInput").value = lastIp;
	com.get("connectServer").onclick=()=>{
		let ip = com.get("ipInput").value;
		net.connect(ip);
		localStorage.setItem("ip",ip);
	};
	com.get("createRoom").onclick=()=>{
		net.send(JSON.stringify({_:"createRoom", type:"jump", count:"2"}));
	};
	com.get("joinRoom").onclick=()=>{
		net.send(JSON.stringify({_:"getRoom", type:"jump"}));
	};
	com.get("quitRoom").onclick=()=>{
		if(net.isInRoom){
			net.isInRoom = false;
			net.send(JSON.stringify({_:"quitRoom"}));
			if(net.isHost)
				com.log("你解散了房间");
			else
				com.log("你离开了房间");
		}else{
			alert("你不在房间内");
		}
	};
	com.get("startGame").onclick=()=>{
		if(net.isInRoom){
			if(play.selfReady)
				alert("你已经准备过了");
			else
				net.send(JSON.stringify({_:"ready", user:net.userId}));
		}else{
			alert("你不在房间内");
		}
	};
	com.get("sendChat").onclick=()=>{
		if(net.isInRoom){
			net.send(JSON.stringify({_:"chat", user:net.userId, chat:com.get("chatInput").value}));
			com.get("chatInput").value = "";
		}else{
			alert("你不在房间内");
		}
	};
	com.get("retract").onclick=()=>{
		if(net.isInRoom){
			if(play.isPlay && play.my != play.turn && play.lastMove){
				net.send(JSON.stringify({_:"retract", user:net.userId}));
			}
		}else{
			alert("你不在房间内");
		}
	};
	com.get("createRoomCancel").onclick=()=>{
		net.isInRoom=false;
		com.get('createRoomDlg').close();
		net.send(JSON.stringify({_:'quitRoom'}));
		com.log("你解散了房间");
	};
}
com.getDomXY = function (dom){
	var left = dom.offsetLeft;
	var top = dom.offsetTop;
	var current = dom.offsetParent;
	while (current !== null){
		left += current.offsetLeft;
		top += current.offsetTop;
		current = current.offsetParent;
	}
	return {x:left,y:top};
}
com.log = function(msg){
	let div = document.createElement("div");
	div.innerHTML = msg;
	let info = com.get("info");
	if(info.childElementCount == 0)
		info.appendChild(div);
	else{
		if(info.childElementCount > 3)
			info.removeChild(info.lastChild);
		info.insertBefore(div, info.firstChild);
	}
}
com.init();